home *** CD-ROM | disk | FTP | other *** search
/ Atari Mega Archive 1 / Atari Mega Archive - Volume 1.iso / gnu / bash / bash_108 / bash-108.zoo / src / glob.c < prev    next >
Encoding:
C/C++ Source or Header  |  1991-08-22  |  13.9 KB  |  628 lines

  1. /* File-name wildcard pattern matching for GNU.
  2.    Copyright (C) 1985, 1988, 1989 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 1, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18. /* To whomever it may concern: I have never seen the code which most
  19.    Unix programs use to perform this function.  I wrote this from scratch
  20.    based on specifications for the pattern matching.  --RMS.  */
  21.  
  22. #include "config.h"
  23.  
  24. #if defined (USG) && !defined (Xenix)
  25. #  define USGr3
  26. #endif
  27.  
  28. #include <sys/types.h>
  29.  
  30. #if defined (USGr3) || defined (DIRENT)
  31. #  include <dirent.h>
  32. #  define direct dirent
  33. #  define    D_NAMLEN(d) strlen((d)->d_name)
  34. #else
  35. #  define D_NAMLEN(d) ((d)->d_namlen)
  36. #  if defined (Xenix)
  37. #    include <sys/ndir.h>
  38. #  else
  39. #    if defined (USG)
  40. #      include "ndir.h"
  41. #     else
  42. #      include <sys/dir.h>
  43. #    endif
  44. #  endif
  45. #endif    /* USGr3 || DIRENT.  */
  46.  
  47. #if defined (_POSIX_SOURCE)
  48. /* Posix does not require that the d_ino field be present, and some
  49.    systems do not provide it. */
  50. #define REAL_DIR_ENTRY(dp) 1
  51. #else
  52. #define REAL_DIR_ENTRY(dp) (dp->d_ino != 0)
  53. #endif /* _POSIX_SOURCE */
  54.  
  55.  
  56. #if defined (NeXT)
  57. #include <string.h>
  58. #else
  59. #if defined (USG)
  60. #if !defined (isc386)
  61. #  include <memory.h>
  62. #endif
  63. #include <string.h>
  64. #if defined (RISC6000)
  65. extern void bcopy ();
  66. #else /* RISC6000 */
  67. #define bcopy(s, d, n) ((void) memcpy ((d), (s), (n)))
  68. #endif /* RISC6000 */
  69. #define rindex    strrchr
  70.  
  71. #else /* !USG */
  72. #include <strings.h>
  73.  
  74. extern void bcopy ();
  75. #endif /* !USG */
  76. #endif /* !NeXT */
  77.  
  78. /* If the opendir () on your system lets you open non-directory files,
  79.    then we consider that not robust.  Define OPENDIR_NOT_ROBUST in the
  80.    SYSDEP_CFLAGS for your machines entry in machines.h. */
  81. #if defined (OPENDIR_NOT_ROBUST)
  82. #if defined (SHELL)
  83. # include "posixstat.h"
  84. #else
  85. # include <sys/stat.h>
  86. #endif /* SHELL */
  87. #endif /* OPENDIR_NOT_ROBUST */
  88.  
  89. extern char *malloc (), *realloc ();
  90. extern void free ();
  91.  
  92. #ifndef NULL
  93. #define NULL 0
  94. #endif
  95.  
  96. /* Global variable which controls whether or not * matches .*.
  97.    Non-zero means don't match .*.  */
  98. int noglob_dot_filenames = 1;
  99.  
  100.  
  101. static int glob_match_after_star ();
  102.  
  103. /* Return nonzero if PATTERN has any special globbing chars in it.  */
  104. int
  105. glob_pattern_p (pattern)
  106.      char *pattern;
  107. {
  108.   register char *p = pattern;
  109.   register char c;
  110.   int    open = 0;
  111.  
  112.   while ((c = *p++) != '\0')
  113.     switch (c)
  114.       {
  115.       case '?':
  116.       case '*':
  117.     return 1;
  118.  
  119.       case '[':        /* Only accept an open brace if there is a close */
  120.     open++;        /* brace to match it.  Bracket expressions must be */
  121.     continue;    /* complete, according to Posix.2 */
  122.       case ']':
  123.     if (open)
  124.       return 1;
  125.     continue;      
  126.  
  127.       case '\\':
  128.     if (*p++ == '\0')
  129.       return 0;
  130.       }
  131.  
  132.   return 0;
  133. }
  134.  
  135. /* Match the pattern PATTERN against the string TEXT;
  136.    return 1 if it matches, 0 otherwise.
  137.  
  138.    A match means the entire string TEXT is used up in matching.
  139.  
  140.    In the pattern string, `*' matches any sequence of characters,
  141.    `?' matches any character, [SET] matches any character in the specified set,
  142.    [!SET] matches any character not in the specified set.
  143.  
  144.    A set is composed of characters or ranges; a range looks like
  145.    character hyphen character (as in 0-9 or A-Z).
  146.    [0-9a-zA-Z_] is the set of characters allowed in C identifiers.
  147.    Any other character in the pattern must be matched exactly.
  148.  
  149.    To suppress the special syntactic significance of any of `[]*?!-\',
  150.    and match the character exactly, precede it with a `\'.
  151.  
  152.    If DOT_SPECIAL is nonzero,
  153.    `*' and `?' do not match `.' at the beginning of TEXT.  */
  154.  
  155. int
  156. glob_match (pattern, text, dot_special)
  157.      char *pattern, *text;
  158.      int dot_special;
  159. {
  160.   register char *p = pattern, *t = text;
  161.   register char c;
  162.  
  163.   while ((c = *p++) != '\0')
  164.     switch (c)
  165.       {
  166.       case '?':
  167.     if (*t == '\0' || (dot_special && t == text && *t == '.'))
  168.       return 0;
  169.     else
  170.       ++t;
  171.     break;
  172.  
  173.       case '\\':
  174.     if (*p++ != *t++)
  175.       return 0;
  176.     break;
  177.  
  178.       case '*':
  179.     if (dot_special && t == text && *t == '.')
  180.       return 0;
  181.     return glob_match_after_star (p, t);
  182.  
  183.       case '[':
  184.     {
  185.       register char c1 = *t++;
  186.       int invert;
  187.  
  188.       if (!c1)
  189.         return (0);
  190.  
  191.       invert = ((*p == '!') || (*p == '^'));
  192.       if (invert)
  193.         p++;
  194.  
  195.       c = *p++;
  196.       while (1)
  197.         {
  198.           register char cstart = c, cend = c;
  199.  
  200.           if (c == '\\')
  201.         {
  202.           cstart = *p++;
  203.           cend = cstart;
  204.         }
  205.  
  206.           if (c == '\0')
  207.         return 0;
  208.  
  209.           c = *p++;
  210.           if (c == '-')
  211.         {
  212.           cend = *p++;
  213.           if (cend == '\\')
  214.             cend = *p++;
  215.           if (cend == '\0')
  216.             return 0;
  217.           c = *p++;
  218.         }
  219.           if (c1 >= cstart && c1 <= cend)
  220.         goto match;
  221.           if (c == ']')
  222.         break;
  223.         }
  224.       if (!invert)
  225.         return 0;
  226.       break;
  227.  
  228.     match:
  229.       /* Skip the rest of the [...] construct that already matched.  */
  230.       while (c != ']')
  231.         { 
  232.           if (c == '\0')
  233.         return 0;
  234.           c = *p++;
  235.           if (c == '\0')
  236.         return 0;
  237.           else if (c == '\\')
  238.         ++p;
  239.         }
  240.       if (invert)
  241.         return 0;
  242.       break;
  243.     }
  244.  
  245.       default:
  246.     if (c != *t++)
  247.       return 0;
  248.       }
  249.  
  250.   return *t == '\0';
  251. }
  252.  
  253. /* Like glob_match, but match PATTERN against any final segment of TEXT.  */
  254.  
  255. static int
  256. glob_match_after_star (pattern, text)
  257.      char *pattern, *text;
  258. {
  259.   register char *p = pattern, *t = text;
  260.   register char c, c1;
  261.  
  262.   while ((c = *p++) == '?' || c == '*')
  263.     if (c == '?' && *t++ == '\0')
  264.       return 0;
  265.  
  266.   if (c == '\0')
  267.     return 1;
  268.  
  269.   if (c == '\\')
  270.     c1 = *p;
  271.   else
  272.     c1 = c;
  273.  
  274.   while (1)
  275.     {
  276.       if ((c == '[' || *t == c1) && glob_match (p - 1, t, 0))
  277.     return 1;
  278.       if (*t++ == '\0')
  279.     return 0;
  280.     }
  281. }
  282.  
  283. /* Return a vector of names of files in directory DIR
  284.    whose names match glob pattern PAT.
  285.    The names are not in any particular order.
  286.    Wildcards at the beginning of PAT do not match an initial period.
  287.  
  288.    The vector is terminated by an element that is a null pointer.
  289.  
  290.    To free the space allocated, first free the vector's elements,
  291.    then free the vector.
  292.  
  293.    Return 0 if cannot get enough memory to hold the pointer
  294.    and the names.
  295.  
  296.    Return -1 if cannot access directory DIR.
  297.    Look in errno for more information.  */
  298.  
  299. char **
  300. glob_vector (pat, dir)
  301.      char *pat;
  302.      char *dir;
  303. {
  304.   struct globval
  305.     {
  306.       struct globval *next;
  307.       char *name;
  308.     };
  309.  
  310.   DIR *d;
  311.   register struct direct *dp;
  312.   struct globval *lastlink;
  313.   register struct globval *nextlink;
  314.   register char *nextname;
  315.   unsigned int count;
  316.   int lose;
  317.   register char **name_vector;
  318.   register unsigned int i;
  319. #if defined (OPENDIR_NOT_ROBUST)
  320.   struct stat finfo;
  321.  
  322.   if (stat (dir, &finfo) < 0)
  323.     return ((char **)-1);
  324.  
  325.   if (!S_ISDIR (statbuf.st_mode))
  326.     return ((char **)-1);
  327. #endif /* OPENDIR_NOT_ROBUST */
  328.  
  329.   d = opendir (dir);
  330.   if (d == NULL)
  331.     return (char **) -1;
  332.  
  333.   lastlink = 0;
  334.   count = 0;
  335.   lose = 0;
  336.  
  337.   /* Scan the directory, finding all names that match.
  338.      For each name that matches, allocate a struct globval
  339.      on the stack and store the name in it.
  340.      Chain those structs together; lastlink is the front of the chain.  */
  341.   while (1)
  342.     {
  343. #if defined (SHELL)
  344.       /* Make globbing interruptible in the bash shell. */
  345.       extern int interrupt_state;
  346.  
  347.       if (interrupt_state)
  348.     {
  349.       closedir (d);
  350.       lose = 1;
  351.       goto lost;
  352.     }
  353. #endif /* SHELL */
  354.       
  355.       dp = readdir (d);
  356.       if (dp == NULL)
  357.     break;
  358.       if (REAL_DIR_ENTRY (dp) &&
  359.       glob_match (pat, dp->d_name, noglob_dot_filenames))
  360.     {
  361.       nextlink = (struct globval *) alloca (sizeof (struct globval));
  362.       nextlink->next = lastlink;
  363.       nextname = (char *) malloc (D_NAMLEN(dp) + 1);
  364.       if (nextname == NULL)
  365.         {
  366.           lose = 1;
  367.           break;
  368.         }
  369.       lastlink = nextlink;
  370.       nextlink->name = nextname;
  371.       bcopy (dp->d_name, nextname, D_NAMLEN(dp) + 1);
  372.       ++count;
  373.     }
  374.     }
  375.   (void) closedir (d);
  376.  
  377.   if (!lose)
  378.     {
  379.       name_vector = (char **) malloc ((count + 1) * sizeof (char *));
  380.       lose |= name_vector == NULL;
  381.     }
  382.  
  383.   /* Have we run out of memory?     */
  384.  lost:
  385.   if (lose)
  386.     {
  387.       /* Here free the strings we have got.  */
  388.       while (lastlink)
  389.     {
  390.       free (lastlink->name);
  391.       lastlink = lastlink->next;
  392.     }
  393.       return NULL;
  394.     }
  395.  
  396.   /* Copy the name pointers from the linked list into the vector.  */
  397.   for (i = 0; i < count; ++i)
  398.     {
  399.       name_vector[i] = lastlink->name;
  400.       lastlink = lastlink->next;
  401.     }
  402.  
  403.   name_vector[count] = NULL;
  404.   return name_vector;
  405. }
  406.  
  407. /* Return a new array which is the concatenation
  408.    of each string in ARRAY to DIR. */
  409.  
  410. static char **
  411. glob_dir_to_array (dir, array)
  412.      char *dir, **array;
  413. {
  414.   register unsigned int i, l;
  415.   int add_slash;
  416.   char **result;
  417.  
  418.   l = strlen (dir);
  419.   if (l == 0)
  420.     return array;
  421.  
  422.   add_slash = dir[l - 1] != '/';
  423.  
  424.   i = 0;
  425.   while (array[i] != NULL)
  426.     ++i;
  427.  
  428.   result = (char **) malloc ((i + 1) * sizeof (char *));
  429.   if (result == NULL)
  430.     return NULL;
  431.  
  432.   for (i = 0; array[i] != NULL; i++)
  433.     {
  434.       result[i] = (char *) malloc (l + (add_slash ? 1 : 0)
  435.                    + strlen (array[i]) + 1);
  436.       if (result[i] == NULL)
  437.     return NULL;
  438.       sprintf (result[i], "%s%s%s", dir, add_slash ? "/" : "", array[i]);
  439.     }
  440.   result[i] = NULL;
  441.  
  442.   /* Free the input array.  */
  443.   for (i = 0; array[i] != NULL; i++)
  444.     free (array[i]);
  445.   free ((char *) array);
  446.  
  447.   return result;
  448. }
  449.  
  450. /* Do globbing on PATHNAME.  Return an array of pathnames that match,
  451.    marking the end of the array with a null-pointer as an element.
  452.    If no pathnames match, then the array is empty (first element is null).
  453.    If there isn't enough memory, then return NULL.
  454.    If a file system error occurs, return -1; `errno' has the error code.  */
  455. char **
  456. glob_filename (pathname)
  457.      char *pathname;
  458. {
  459.   char **result;
  460.   unsigned int result_size;
  461.   char *directory_name, *filename;
  462.   unsigned int directory_len;
  463.  
  464.   result = (char **) malloc (sizeof (char *));
  465.   result_size = 1;
  466.   if (result == NULL)
  467.     return NULL;
  468.  
  469.   result[0] = NULL;
  470.  
  471.   /* Find the filename.  */
  472.   filename = rindex (pathname, '/');
  473.   if (filename == NULL)
  474.     {
  475.       filename = pathname;
  476.       directory_name = "";
  477.       directory_len = 0;
  478.     }
  479.   else
  480.     {
  481.       directory_len = (filename - pathname) + 1;
  482.       directory_name = (char *) alloca (directory_len + 1);
  483.  
  484.       bcopy (pathname, directory_name, directory_len);
  485.       directory_name[directory_len] = '\0';
  486.       ++filename;
  487.     }
  488.  
  489.   /* If directory_name contains globbing characters, then we
  490.      have to expand the previous levels.  Just recurse. */
  491.   if (glob_pattern_p (directory_name))
  492.     {
  493.       char **directories;
  494.       register unsigned int i;
  495.  
  496.       if (directory_name[directory_len - 1] == '/')
  497.     directory_name[directory_len - 1] = '\0';
  498.  
  499.       directories = glob_filename (directory_name);
  500.  
  501.       if (directories == NULL)
  502.     goto memory_error;
  503.       else if ((int) directories == -1)
  504.     return (char **) -1;
  505.       else if (*directories == NULL)
  506.     {
  507.       free ((char *) directories);
  508.       return (char **) -1;
  509.     }
  510.  
  511.       /* We have successfully globbed the preceding directory name.
  512.      For each name in DIRECTORIES, call glob_vector on it and
  513.      FILENAME.  Concatenate the results together.  */
  514.       for (i = 0; directories[i] != NULL; ++i)
  515.     {
  516.       char **temp_results = glob_vector (filename, directories[i]);
  517.  
  518.       /* Handle error cases. */
  519.       if (temp_results == NULL)
  520.         goto memory_error;
  521.       else if (temp_results == (char **)-1)
  522.         /* This filename is probably not a directory.  Ignore it.  */
  523.         ;
  524.       else
  525.         {
  526.           char **array = glob_dir_to_array (directories[i], temp_results);
  527.           register unsigned int l;
  528.  
  529.           l = 0;
  530.           while (array[l] != NULL)
  531.         ++l;
  532.  
  533.           result =
  534.         (char **)realloc (result, (result_size + l) * sizeof (char *));
  535.  
  536.           if (result == NULL)
  537.         goto memory_error;
  538.  
  539.           for (l = 0; array[l] != NULL; ++l)
  540.         result[result_size++ - 1] = array[l];
  541.  
  542.           result[result_size - 1] = NULL;
  543.  
  544.           /* Note that the elements of ARRAY are not freed.  */
  545.           free ((char *) array);
  546.         }
  547.     }
  548.       /* Free the directories.  */
  549.       for (i = 0; directories[i]; i++)
  550.     free (directories[i]);
  551.  
  552.       free ((char *) directories);
  553.  
  554.       return result;
  555.     }
  556.  
  557.   /* If there is only a directory name, return it. */
  558.   if (*filename == '\0')
  559.     {
  560.       result = (char **) realloc ((char *) result, 2 * sizeof (char *));
  561.       if (result == NULL)
  562.     return NULL;
  563.       result[0] = (char *) malloc (directory_len + 1);
  564.       if (result[0] == NULL)
  565.     goto memory_error;
  566.       bcopy (directory_name, result[0], directory_len + 1);
  567.       result[1] = NULL;
  568.       return result;
  569.     }
  570.   else
  571.     {
  572.       /* Otherwise, just return what glob_vector
  573.      returns appended to the directory name. */
  574.       char **temp_results = glob_vector (filename,
  575.                      (directory_len == 0
  576.                       ? "." : directory_name));
  577.  
  578.       if (temp_results == NULL || temp_results == (char **)-1)
  579.     return temp_results;
  580.  
  581.       return glob_dir_to_array (directory_name, temp_results);
  582.     }
  583.  
  584.   /* We get to memory error if the program has run out of memory, or
  585.      if this is the shell, and we have been interrupted. */
  586.  memory_error:
  587.   if (result != NULL)
  588.     {
  589.       register unsigned int i;
  590.       for (i = 0; result[i] != NULL; ++i)
  591.     free (result[i]);
  592.       free ((char *) result);
  593.     }
  594. #if defined (SHELL)
  595.   {
  596.     extern int interrupt_state;
  597.  
  598.     if (interrupt_state)
  599.       throw_to_top_level ();
  600.   }
  601. #endif /* SHELL */
  602.   return NULL;
  603. }
  604.  
  605. #ifdef TEST
  606.  
  607. main (argc, argv)
  608.      int argc;
  609.      char **argv;
  610. {
  611.   unsigned int i;
  612.  
  613.   for (i = 1; i < argc; ++i)
  614.     {
  615.       char **value = glob_filename (argv[i]);
  616.       if (value == NULL)
  617.     puts ("Out of memory.");
  618.       else if ((int) value == -1)
  619.     perror (argv[i]);
  620.       else
  621.     for (i = 0; value[i] != NULL; i++)
  622.       puts (value[i]);
  623.     }
  624.  
  625.   exit (0);
  626. }
  627. #endif    /* TEST.  */
  628.